package com.newland.mesdk.demo.device;

import android.util.Log;

import com.newland.mtypex.usb.UsbV100ConnParams;
import com.newland.mesdk.demo.activity.BaseActivity;
import com.newland.mesdk.demo.main.MainActivity;
import com.newland.mesdk.demo.moduleinterface.DeviceControllerInterface;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * Created by YJF USB连接设备
 */
public class USBDevice extends AbstractDevice {
	private static final String ME3X_DRIVER_NAME = "com.newland.me.ME3xDriver";
	private BaseActivity baseActivity;
	private DeviceControllerInterface controller = null;
	private String TAG = MainActivity.class.getName();

	public USBDevice(BaseActivity baseActivity) {
		this.baseActivity = baseActivity;
	}

	@Override
	public void initController() {
		ME3xDeviceDriver me3xDeviceController = new ME3xDeviceDriver(baseActivity);
		controller = me3xDeviceController.initMe3xDeviceController(ME3X_DRIVER_NAME, new UsbV100ConnParams());
		baseActivity.btnStateToWaitingConn();
	}

	@Override
	public void disconnect() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					if (controller != null) {
						controller.disConnect();
						controller = null;
						baseActivity.showMessage("USB控制器断开成功...", MessageTag.TIP);
						baseActivity.btnStateToWaitingInit();
					}
				} catch (Exception e) {
					Log.e(TAG, "USb disconnect failed!", e);
					baseActivity.showMessage("USB控制器断开异常："+e, MessageTag.ERROR);
				}
			}
		}).start();

	}

	@Override
	public boolean isControllerAlive() {
		if (controller != null) {
			return true;
		}
		return false;
	}

	@Override
	public DeviceControllerInterface getController() {
		return controller;
	}

	@Override
	public void connectDevice() {
		baseActivity.showMessage("USB设备连接中....", MessageTag.TIP);
		try {
			controller.connect();
			baseActivity.showMessage("USB设备连接成功...", MessageTag.TIP);
		} catch (Exception e1) {
			e1.printStackTrace();
			baseActivity.showMessage("USB链接异常,请检查设备或重新连接:" + e1, MessageTag.ERROR);

		}
	}
}
